<template>
  <div class="readerBorrowHistory">
    <h2>我的借阅</h2>
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="当前借阅" name="current"></el-tab-pane>
      <el-tab-pane label="历史借阅" name="history"></el-tab-pane>
    </el-tabs>

    <el-table :data="borrowList" style="width: 100%" v-loading="loading">
      <el-table-column prop="bookname" label="图书名称"></el-table-column>
      <el-table-column prop="borrowtime" label="借阅日期">
        <template slot-scope="scope">
          {{ scope.row.borrowtime | formatDate }}
        </template>
      </el-table-column>
      <el-table-column prop="returntime" label="应还日期">
        <template slot-scope="scope">
          {{ scope.row.returntime | formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 0 ? 'warning' : 'success'">
            {{ scope.row.status === 0 ? '借阅中' : '已归还' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-if="activeTab === 'current'">
        <template slot-scope="scope">
          <el-button
              size="mini"
              type="success"
              @click="handleReturn(scope.row.borrowid)"
          >归还</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
        background
        style="margin-top: 20px; text-align: right;"
    ></el-pagination>
  </div>
</template>

<script>
import { getMyCurrentBorrowsByUsername, getMyBorrowHistoryByUsername, returnBook } from '@/api/api';

export default {
  name: 'ReaderBorrowHistory',
  data() {
    return {
      activeTab: 'current', // current: 当前借阅, history: 历史借阅
      borrowList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10, // 与后端分页大小保持一致
      total: 0
    };
  },
  filters: {
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      if (isNaN(date.getTime())) {
        console.warn("Invalid date string for formatDate:", dateString);
        return dateString;
      }
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  },
  created() {
    this.fetchBorrowList();
  },
  methods: {
    fetchBorrowList() {
      this.loading = true;
      const username = localStorage.getItem('username'); // 获取用户名

      if (!username) {
        this.$message.error('用户信息缺失（用户名），请重新登录');
        this.$router.push('/login');
        this.loading = false;
        return;
      }

      let apiCall;
      if (this.activeTab === 'current') {
        apiCall = getMyCurrentBorrowsByUsername(this.currentPage, username);
      } else {
        apiCall = getMyBorrowHistoryByUsername(this.currentPage, username);
      }

      apiCall.then(res => {
        if (res.code === 200) {
          this.borrowList = res.data.list;
          this.total = res.data.total;
        } else {
          this.$message.error(res.msg || '获取借阅信息失败');
        }
      })
          .catch(error => {
            console.error("获取借阅信息请求失败:", error);
            this.$message.error('获取借阅信息异常，请稍后再试');
          })
          .finally(() => {
            this.loading = false;
          });
    },
    handleReturn(borrowid) {
      this.$confirm('确定要归还此图书吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        returnBook(borrowid)
            .then(res => {
              if (res.code === 200) {
                this.$message.success('归还成功！');
                this.fetchBorrowList(); // 归还成功后刷新列表
              } else {
                this.$message.error(res.msg || '归还失败');
              }
            })
            .catch(error => {
              console.error("归还请求失败:", error);
              this.$message.error('归还请求异常，请稍后再试');
            });
      }).catch(() => {
        this.$message.info('已取消归还');
      });
    },
    handlePageChange(newPage) {
      this.currentPage = newPage;
      this.fetchBorrowList();
    },
    handleTabClick() {
      this.currentPage = 1; // 切换tab时重置页码为1
      this.fetchBorrowList();
    }
  }
};
</script>

<style scoped>
/* 可选的样式 */
</style>